Skip to content

src: detach cppgc wrappers from their Realm before it is freed - #65778

Open
codebytere wants to merge 1 commit into
nodejs:mainfrom
codebytere:fix/embedder-cppgc-wrapper-realm-lifetime
Open

src: detach cppgc wrappers from their Realm before it is freed#65778
codebytere wants to merge 1 commit into
nodejs:mainfrom
codebytere:fix/embedder-cppgc-wrapper-realm-lifetime

Conversation

@codebytere

@codebytere codebytere commented Sep 4, 2026

Copy link
Copy Markdown
Member

A vm.Script (or any other cppgc-managed wrapper) that is garbage-collected shortly before its Environment is freed, but whose destructor only runs afterwards, writes into the already-freed Realm from ~CppgcMixin(). With a stock node binary this happens in a Worker that compiles a few scripts, gets a full GC from external memory pressure and then calls process.exit(): ASAN reports a heap-use-after-free write in ~ContextifyScript while the Worker's isolate is being disposed. Embedders that free Environments on a long-lived isolate (Electron renderers) hit it during a later sweep instead.

Realm::RunCleanup() is meant to detach every tracked wrapper from the Realm before the Realm goes away, but it reaches the wrappers through weak persistents. V8 clears those as soon as marking finds a wrapper dead, while the destructor runs later during lazy or concurrent sweeping, so wrappers in that window are skipped and keep their Realm pointer. A subclass using the documented ~MyWrap() { Finalize(); } pattern would call Clean() with a dangling Realm the same way.

Once V8 has found a wrapper dead, nothing but its own destructor may touch it, so the fix moves the Realm pointer out of the wrapper and into the off-heap list node, which the wrapper now owns and frees in its destructor. Realm cleanup pops every node, finalizes the wrappers that are still alive and clears the Realm pointer on all of them; a collected wrapper's destructor then finds no Realm rather than a freed one.

Realm::PendingCleanup() counts the wrapper list as well so cleanup always drains it. The purge flag, its GC epilogue callback and PurgeEmpty() are no longer needed and are removed, which also stops the list nodes of wrappers still alive at FreeEnvironment() from leaking.

Tests, in test/cctest/test_cppgc.cc:

  • CppgcTest.VmScriptCollectedBeforeFreeEnvironmentSweptAfter: the scenario above; heap-use-after-free under ASAN before the change.
  • CppgcTest.CleanIsNotCalledWithFreedRealm: a wrapper using the Finalize() / Clean() pattern; fails before the change (every run under ASAN, roughly one run in three in a regular build, depending on whether the sweeper got there first).
  • CppgcTest.WrappersAliveAtFreeEnvironmentDoNotLeak: reported by LSAN before the change.

Refs: #56534


Disclosure: the code, tests and this description were written by Claude Code, directed and reviewed by @codebytere.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/realm
  • @nodejs/startup

@nodejs-github-bot nodejs-github-bot added c++ Issues and PRs that require attention from people who are familiar with C++. lib / src Issues and PRs involving general changes in the lib/ or src/ directories. needs-ci PRs that need a full CI run. labels Sep 4, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

`Realm::RunCleanup()` finalizes the cppgc-managed wrappers it tracks
so that none of them touches the Realm once it is gone, but it reaches
them through weak persistents, and the GC clears those as soon as it
finds a wrapper dead. With lazy and concurrent sweeping the destructor
can run much later, so a wrapper collected shortly before
`FreeEnvironment()` and swept after it was skipped by the cleanup and
kept its `realm_`: `~CppgcMixin()` then wrote
`should_purge_empty_cppgc_wrappers_` into the freed Realm, and a
subclass destructor calling `Finalize()` as documented would have
called `Clean()` with a dangling Realm. A Worker that compiles a few
`vm.Script`s, gets a full GC from external memory pressure and calls
`process.exit()` is enough to hit the first case.

Move the Realm pointer into the list node, which the wrapper now owns
and deletes in its destructor. `CppgcWrapperList::Cleanup()` unlinks
every node, finalizing the wrappers that are still alive and clearing
the Realm pointer for the collected ones, which only their own
destructor may still touch. `Realm::PendingCleanup()` accounts for the
list so it is always drained. The purge flag, its GC epilogue callback
and `PurgeEmpty()` are no longer needed, and removing them also stops
the list nodes of wrappers that are alive at `FreeEnvironment()` from
leaking.

Refs: nodejs#56534
Signed-off-by: Shelley Vohr <[email protected]>
@codebytere
codebytere force-pushed the fix/embedder-cppgc-wrapper-realm-lifetime branch from bbc133a to 6bb6296 Compare September 4, 2026 08:45
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@codecov

codecov Bot commented Sep 4, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.05%. Comparing base (2befec5) to head (6bb6296).
⚠️ Report is 82 commits behind head on main.

Files with missing lines Patch % Lines
src/cppgc_helpers-inl.h 81.81% 0 Missing and 2 partials ⚠️
src/node_realm.cc 0.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #65778      +/-   ##
==========================================
+ Coverage   89.99%   90.05%   +0.05%     
==========================================
  Files         757      769      +12     
  Lines      257739   261377    +3638     
  Branches    48881    49629     +748     
==========================================
+ Hits       231961   235377    +3416     
- Misses      16861    17033     +172     
- Partials     8917     8967      +50     
Files with missing lines Coverage Δ
src/cppgc_helpers.cc 64.28% <100.00%> (-27.39%) ⬇️
src/cppgc_helpers.h 60.00% <100.00%> (-33.34%) ⬇️
src/node_realm-inl.h 91.93% <100.00%> (+0.26%) ⬆️
src/node_realm.h 100.00% <ø> (ø)
src/node_realm.cc 75.47% <0.00%> (-1.18%) ⬇️
src/cppgc_helpers-inl.h 85.71% <81.81%> (-0.96%) ⬇️

... and 79 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@mcollina mcollina left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RSLGTM

@mcollina mcollina added the request-ci Add this label to start a Jenkins CI on a PR. label Sep 4, 2026
@mcollina
mcollina requested a review from legendecas September 4, 2026 14:36
@github-actions github-actions Bot removed the request-ci Add this label to start a Jenkins CI on a PR. label Sep 4, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

c++ Issues and PRs that require attention from people who are familiar with C++. lib / src Issues and PRs involving general changes in the lib/ or src/ directories. needs-ci PRs that need a full CI run.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants